<template>
  <div id="app">
    <div class="search">
      <span>
        <el-date-picker
            v-model="sateValue"
            type="daterange"
            range-separator="至"
            clearable
            size="small"
            @change="selectTime"
            style="width: 300px"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        >
        </el-date-picker>
      </span>
      <span style="margin-left: 10px">
        <el-input
            size="small"
            style="width: 200px"
            clearable
            v-model="params.storeName"
            placeholder="输入店铺名称搜索"
            clearable
        ></el-input>
      </span>
      <span style="text-align: center; margin-left: 20px">
        <el-select
            v-model="params.areaId"
            clearable
            clearable
            placeholder="按仓库搜索"
            size="small"
            style="width: 180px"
        >
          <el-option
              v-for="item in areaData"
              :key="item.area"
              :label="item.areaName"
              :value="item.area"
          >
          </el-option>
        </el-select>
      </span>
      <span style="text-align: center; margin-left: 20px">
        <el-select
            v-model="params.commissionTypeId"
            clearable
            style="width: 180px"
            size="small"
            placeholder="按提成类型搜索"
        >
          <el-option
              v-for="(item, index) in commissionList"
              :label="item.commissionType"
              :value="item.id"
              :key="index"
          ></el-option>
        </el-select>
      </span>
      <!--      <span style="text-align: center; margin-left: 20px">-->
      <!--        <el-select-->
      <!--            v-model="params.status"-->
      <!--            clearable-->
      <!--            style="width: 180px"-->
      <!--            size="small"-->
      <!--            placeholder="按状态搜索"-->
      <!--        >-->
      <!--          <el-option label="待分配" value="0"></el-option>-->
      <!--          <el-option label="待审核" value="1"></el-option>-->
      <!--          <el-option label="审核通过" value="2"></el-option>-->
      <!--          <el-option label="审核拒绝" value="3"></el-option>-->
      <!--          <el-option label="已取消" value="4"></el-option>-->
      <!--        </el-select>-->
      <!--      </span>-->
      <span style="text-align: center; margin-left: 20px">
        <el-select
            clearable
            v-model="params.brandId"
            placeholder="按品牌方搜索"
            size="small"
            style="width: 200px"
        >
          <el-option
              v-for="item in systemTypeData"
              :key="item.id"
              :label="item.systemName"
              :value="item.id"
          >
          </el-option> </el-select
        ></span>
      <span style="text-align: center; margin-left: 20px">
        <el-input
            clearable
            v-model="params.picker"
            placeholder="按提成姓名搜索"
            size="small"
            style="width: 200px"
        ></el-input
        ></span>
      <el-button
          size="small"
          type="primary"
          style="margin-left: 10px"
          @click="search"
      >搜索
      </el-button
      >
      <el-button
          size="small"
          type="primary"
          v-if="authority.includes(1131)"
          style="margin-right: 10px"
          @click="_add"
      ><i class="el-icon-plus"></i>新增提成
      </el-button>
      <el-button
          size="small"
          type="primary"
          @click="_down"
          v-if="authority.includes(1060)"
      ><i class="el-icon-download"></i>导出
      </el-button>
      <div class="download" style="float: right">
        <!--        <el-dropdown @command="downloadTotal">-->
        <!--          <el-button type="primary" size="small">-->
        <!--            <i class="el-icon-download"></i>-->
        <!--            提成汇总下载-->
        <!--          </el-button>-->
        <!--          <el-dropdown-menu slot="dropdown">-->
        <!--            <el-dropdown-item :command="''">全部</el-dropdown-item>-->
        <!--            <el-dropdown-item :command="item.id" v-for="item in systemTypeData">{{ item.systemName }}</el-dropdown-item>-->
        <!--          </el-dropdown-menu>-->
        <!--        </el-dropdown>-->
      </div>
    </div>
    <el-checkbox-group v-model="checkboxGroup1" size="small" style="float:right;margin:5px"
                       @change="getStatus">
      <el-checkbox-button v-for="(e, i) in statusList" :label="e.val" :key="i">{{ e.name }}</el-checkbox-button>
    </el-checkbox-group>
    <div class="table">
      <el-table
          class="auto-width-table"
          :data="reportData"
          border
          height="calc(100vh - 280px)"
          v-loading="loading"
          :headerCellStyle="{
          textAlign: 'center',
          background: '#66b1ff',
          color: 'white',
        }"
          :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
      >
        <el-table-column
            type="index"
            label="序号"
            width="60px"
        ></el-table-column>
        <el-table-column
            prop="brand"
            label="品牌"
            width="100px"
        ></el-table-column>
        <el-table-column
            prop="storeName"
            label="店铺名称"
            show-overflow-tooltip
            width="160px"
        ></el-table-column>
        <el-table-column prop="picker" label="提成人姓名" width="150px" show-overflow-tooltip>
          <template v-slot:default="scope">
            <div style="display: flex" v-if="scope.row.picker">
              <el-tag
                  v-for="item in scope.row.picker.split(',')"
                  size="small"
                  style="margin-right: 2px"
              >
                {{ item }}
              </el-tag>
            </div>
            <!--            <span>{{scope.row.picker}}</span>-->
          </template>
        </el-table-column>
        <el-table-column
            prop="tempWorkerNum"
            label="零时工数量"
            width="100px"
        ></el-table-column>
        <el-table-column
            prop="areaName"
            label="仓库"
            width="100px"
        ></el-table-column>
        <el-table-column
            prop="commissionTime"
            label="提成产生时间"
            width="110px"
        ></el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
            width="110px"
        ></el-table-column>
        <el-table-column
            prop="deliveryDate"
            label="去货架时间"
            show-overflow-tooltip
            width="110px"
        ></el-table-column>
        <el-table-column prop="commissionTypeId" label="提成类型" width="100px">
          <template slot-scope="scope">
            <span v-if="scope.row.commissionTypeId == 1" style="color: #ff3546"
            >材料提成</span
            >
            <span v-if="scope.row.commissionTypeId == 2" style="color: #ff6a00"
            >仓库装货提成</span
            >
            <span v-if="scope.row.commissionTypeId == 3" style="color: #ff1493"
            >仓库卸货提成</span
            >
            <span v-if="scope.row.commissionTypeId == 4" style="color: #5daf34"
            >门店卸货提成</span
            >
            <span v-if="scope.row.commissionTypeId == 5" style="color: #4235d5"
            >安装距离补贴</span
            >
            <span v-if="scope.row.commissionTypeId == 6" style="color: #065aa4"
            >新增单提成</span
            >
            <span v-if="scope.row.commissionTypeId == 7" style="color: #cf9236"
            >上门售后提成</span
            >
            <span v-if="scope.row.commissionTypeId == 8" style="color: #13ce66"
            >仓库拣货提成</span
            >
            <span v-if="scope.row.commissionTypeId == 9" style="color: #1370fb"
            >门店安装提成</span
            >
            <span v-if="scope.row.commissionTypeId == 10" style="color: #303e9d"
            >门店拆店提成</span
            >
            <span v-if="scope.row.commissionTypeId == 13" style="color: #303e9d"
            >门店装货提成</span
            >
          </template>
        </el-table-column>
        <el-table-column
            prop="totalCommission"
            label="提成总额"
            width="100px"
        ></el-table-column>
        <el-table-column
            prop="deductCommission"
            label="扣提成"
            width="100px"
        ></el-table-column>
        <el-table-column
            prop="commissionAmount"
            label="最终提成"
            width="100px"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="100px">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0" style="color: #ff6a00"
            >待分配</span
            >
            <span v-if="scope.row.status == 1" style="color: #66b1ff"
            >待审核</span
            >
            <span v-if="scope.row.status == 2" style="color: #67c23a"
            >审核通过</span
            >
            <span v-if="scope.row.status == 3" style="color: #ff3546"
            >审核拒绝</span
            >
            <span v-if="scope.row.status == 4" style="color: #606266"
            >已取消</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" class-name="action-column">
          <template slot-scope="scope">
            <el-link
                type="primary"
                v-if="authority.includes(1132)"
                style="margin-right: 10px"
                @click="getDetail(scope.row)"
            >明细
            </el-link
            >
            <el-link
                type="warning"
                style="margin-right: 10px"
                v-if="!scope.row.picker&&authority.includes(1133)&&scope.row.status!=4"
                @click="distribute(scope.row)"
            >
              分配人员
            </el-link>
            <el-link
                type="warning"
                style="margin-right: 10px"
                v-if="scope.row.status < 2&&authority.includes(1134)"
                @click="cancer(scope.row)"
            >
              取消提成
            </el-link>
            <el-link
                type="danger"
                style="margin-right: 10px"
                @click="audit(scope.row)"
                v-if="scope.row.status == 1"
            >审核
            </el-link>
            <el-link
                type="danger"
                style="margin-right: 10px"
                @click="_delete(scope.row)"
                v-if="scope.row.status == 4"
            >删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="padding: 20px 0"
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
      >
      </el-pagination>
    </div>
    <add ref="addRef" @addStatus="receiveData"></add>
    <el-dialog :visible.sync="chooseDialog" title="分配提成" width="30%" center>
      <div class="box">
        <p style="margin-bottom: 15px">
          <span>提成人员：</span>
          <el-select
              multiple
              v-model="split.pickerList"
              filterable
              style="width: 300px"
              size="small"
              placeholder="请选择提成人员"
          >
            <el-option
                v-for="(item, index) in userList"
                :label="item.userName"
                :value="item.id"
                :key="index"
            ></el-option>
          </el-select>
        </p>
        <div style="width: 400px; margin-bottom: 50px">
          <span>图片凭证:</span>(粘贴复制即可上传图片)
          <div class="div" style="display: flex; align-items: center">
            <div
                v-for="(v, i) in proof"
                style="display: flex; align-items: center; margin-right: 10px"
            >
              <el-image
                  :key="i"
                  style="width: 50px; height: 50px"
                  ref="preview"
                  :src="host + v"
                  :preview-src-list="[host + v]"
              >
              </el-image>
              <div @click="deletePaiedUrl(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
        <div v-if="[1, 2, 3, 4].includes(distributeType)">
          <p style="margin-bottom: 15px">
            <span>零时工人数：</span>
            <el-input-number
                multiple
                v-model="split.tempWorkerNum"
                style="width: 300px"
                size="small"
                placeholder="请输入零时工人数"
            >
            </el-input-number>
          </p>
          <p style="margin-bottom: 15px">
            <span>提成产生时间：</span>
            <el-date-picker
                v-model="split.commissionTime"
                style="width: 300px"
                size="small"
                value-format="yyyy-MM-dd"
                placeholder="请选择提成产生时间"
            >
            </el-date-picker>
          </p>
        </div>
        <div v-if="[2, 3].includes(distributeType)">
          <p>
            <span>车型配置：</span>
            <el-select
                @change="handleChange"
                v-model="split.vehicleModelId"
                style="width: 300px"
                size="small"
                placeholder="请选择车型配置"
            >
              <el-option
                  v-for="(item, index) in carData"
                  :label="item.vehicleModelName"
                  :value="item.id"
                  :key="index"
              ></el-option>
            </el-select>
          </p>
          <p>
            <span>提成金额：</span>
            {{ commissionAmount }}
          </p>
        </div>
        <div v-if="[8].includes(distributeType)" style="width: 75%">
          <p>
            <span style="display: inline-block; width: 130px">店铺名称：</span
            >{{ distributeList.storeName }}
          </p>
          <p>
            <span style="display: inline-block; width: 130px"
            >是否有仓储架捡货：</span
            >{{ distributeList.isStorageRack == 0 ? '否' : '是' }}
          </p>
          <p>
            <span style="display: inline-block; width: 130px"
            >营业区捡货组数：</span
            >{{ distributeList.pickUpGroupNum }}
          </p>
        </div>
      </div>
      <span slot="footer">
        <el-button size="small" @click="chooseDialog = false">取消</el-button>
        <el-button size="small" type="primary" @click="_submit">提交</el-button>
      </span>
    </el-dialog>
    <commission-detail
        ref="detailRef"
        @addStatus="receiveData"
    ></commission-detail>
    <el-dialog :visible.sync="downDialog" width="30%" center title="导出提成" :close-on-click-modal="false">
      <div style="display: flex;align-items: center;flex-direction: column">
        <p style="margin-bottom: 15px">
          <span>选择日期：   <el-date-picker
              v-model="downObj.month"
              type="month"
              size="small"
              value-format="yyyy-MM"
              style="width: 250px"
              placeholder="选择月">
    </el-date-picker></span>
        </p>
        <p>
          <span>选择仓库：  <el-select
              v-model="downObj.areaId"
              size="small"
              style="width: 250px"
              clearable
              placeholder="选择仓库"
          >
          <el-option
              v-for="item in areaData"
              :key="item.area"
              :label="item.areaName"
              :value="item.area"
          >
          </el-option>
        </el-select></span>
        </p>
      </div>
      <span slot="footer">
         <el-progress
             v-if="loadingProgress"
             :percentage="progress"
             :status="progressStatus"
             :stroke-width="16"
             style="margin: 20px 0;"
             :show-text="true"
         ></el-progress>
        <el-button type="primary" @click="comfirmDown" size="small">下 载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import add from './dialogRef/add.vue'
import axios from 'axios'
import store from '../../../store'
import commissionDetail from './commissionDetail.vue'
import quinn from "../../../utils/quinn";

export default {
  name: 'ReportList',
  components: {
    add,
    commissionDetail,
  },
  data() {
    return {
      sateValue: '',
      areaData: [],
      progress: 0,          // 进度百分比
      progressStatus: null,   // success / exception
      split: {tempWorkerNum: 0},
      proof: [],
      commissionAmount: '',
      carData: [],
      distributeType: '',
      pickerList: [],
      userList: [],
      visible: false,
      downDialog: false,
      loadingProgress: false,
      detailData: [],
      loading: false,
      host: this.$imgHost,
      distributeId: '',
      checkboxGroup1: [],
      distributeList: [],
      chooseDialog: false,
      detailDialog: false,
      currentPage: 1,
      totalCount: 0,
      downObj: {},
      systemTypeData: [],
      authority: [],
      statusList: [{
        val: 0,
        name: '待分配'
      }, {
        val: 1,
        name: '待审核'
      }, {
        val: 2,
        name: '审核通过'
      }, {
        val: 3,
        name: '审核拒绝'
      }, {
        val: 4,
        name: '已取消'
      },],
      commissionList: [],
      reportData: [],
      params: {
        pageSize: 20,
        pageNum: 1,
        statusList: [],
        picker: "",
      },
    }
  },
  created() {
    const {authorityList = []} = quinn.getStorage('userData')
    this.authority = authorityList
    this.getReportList()
    this.areaList()
    this.getCommissionType()
    document.addEventListener('paste', this.handlePaste)
  },
  methods: {
    _down() {
      this.downDialog = true
      this.loadingProgress = false
      this.downObj = this.$options.data.call(this).downObj
      // if (!this.params.startTime || !this.params.endTime) return this.$message.warning('请选择开始时间和结束时间！')
      // if (!this.params.areaId) return this.$message.warning('请选择仓库！')
      // this.$api.commissionDetailsGetCommissionMonthSummaryExcel({})
    },
    comfirmDown() {
      if (!this.downObj.month) return this.$message.warning('请选择时间！')
      if (!this.downObj.areaId) return this.$message.warning('请选择仓库！')
      this.loadingProgress = true
      this.progress = 0
      this.progressStatus = null // 进度条状态
      let timer = null
      // 开始模拟进度递增
      timer = setInterval(() => {
        if (this.progress < 90) {
          this.progress += Math.floor(Math.random() * 5) + 1 // 每次递增 1~5%
        }
      }, 200)
      axios({
        url: `${this.$apiHost}/commissionDetails/getCommissionMonthSummaryExcel`,
        method: 'get',
        responseType: 'blob',
        headers: {
          token: window.$quinn.getStorage("token")
        },
        params: this.downObj
      }).then(res => {
        const disposition = res.headers['content-disposition'];
        let fileName = this.downObj.month + '.xlsx'; // 默认给个 .xlsx
        if (disposition) {
          const match = disposition.match(/filename="?([^"]+)"?/);
          if (match) {
            fileName = decodeURIComponent(match[1]);
            // 如果没有后缀，就补 .xlsx
            if (!fileName.includes('.')) {
              fileName += '.xlsx';
            }
          }
        }
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        URL.revokeObjectURL(link.href);
        // 接口返回后，立即让进度条完成
        this.progress = 100
        this.progressStatus = 'success'
        clearInterval(timer)
        this.loadingProgress = false
      });
    },
    getStatus(val) {
      this.params.pageNum = 1
      this.params.statusList = val
      this.getReportList()
    },
    handleChange(val) {
      const selected = this.carData.find((item) => item.id === val)
      if (this.commissionTypeId == 2) {
        this.commissionAmount = selected.pickCommission
      } else {
        this.commissionAmount = selected.unloadCommission
      }
    },
    handlePaste(event) {
      if (!this.chooseDialog) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    deletePaiedUrl(i) {
      // this.editableTabs[this.tabIndex - 1].data.fileList.splice(i, 1)
      this.proof.splice(i, 1)
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
          .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: store.state.token,
            },
          })
          .then((response) => {
            this.proof.push(response.data.result[0])
          })
          .catch((error) => {
          })
    },
    distribute(row) {
      // this.chooseDialog = true
      // this.distributeId = row.id
      // this.distributeList = row
      // this.split = this.$options.data.call(this).split
      // this.proof = []
      // if (row.commissionTypeId == 8) {
      //   this.$api.commissionDetailsSelectPickupGroup({
      //     orderId: row.orderId
      //   }).then(res => {
      //     this.distributeList.isStorageRack = res.isStorageRack
      //     this.distributeList.pickUpGroupNum = res.jhGoodsCount || 0
      //   })
      // }
      // this.distributeType = row.commissionTypeId
      // this.$api.orderSelectInstallationUser({loginType: 4}).then(res => {
      //   this.userList = res
      // })
      // this.$api.vehicleGetVehicleModel().then(res => {
      //   this.carData = res
      // })
      this.$refs.addRef.handleOpen(row)
    },
    _submit() {
      const data = {
        ...this.split,
        proof: this.proof.toString(),
        parentId: this.distributeId,
      }
      this.$api.commissionDetailsDistribution(data).then((res) => {
        if (res) {
          this.$message.success('添加成功！')
          this.chooseDialog = false
          this.getReportList()
        }
      })
    },
    audit(row) {
      this.$refs.detailRef.handleOpen(row, 1)
      // this.$confirm(`审核 ${row.picker} 提成？`, '提示', {
      //   confirmButtonText: '通过',
      //   cancelButtonText: '驳回',
      //   distinguishCancelAndClose: true,
      //   type: 'warning',
      //   confirmButtonClass: 'el-button--success',
      //   cancelButtonClass: 'el-button--danger',
      // })
      //     .then(() => {
      //       this.handleAudit(row, 2, '审核通过！');
      //     })
      //     .catch((action) => {
      //       if (action === 'cancel') {
      //         this.handleAudit(row, 3, '已驳回！');
      //       }
      //     });
    },
    _delete(row) {
      this.$confirm(`删除 ${row.storeName}的${row.commissionTypeName}？`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        //   distinguishCancelAndClose: true,
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        cancelButtonClass: 'el-button--info',
      })
          .then(() => {
            this.$api.commissionDetailsDeleteCommissionDetails({id: row.id}).then(res => {
              if (res) {
                this.$message.success('删除成功!')
                this.getReportList()
              }
            })
          })
          .catch(() => {
          });
    },
    async handleAudit(row, status, message) {
      const data = {id: row.id, status}
      const res = await this.$api.commissionDetailsAuditCommissionDetails(data)
      if (res) {
        this.$message.success(message)
        await this.getReportList()
      }
    },
    getDetail(row) {
      this.$refs.detailRef.handleOpen(row)
    },
    areaList() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.areaData = res
      })
      this.$api.orderGetSystemTypeVo().then((res) => {
        this.systemTypeData = res
      })
    },
    getCommissionType() {
      this.$api.commissionGetCommissionTypes2().then((res) => {
        this.commissionList = res
      })
    },
    async getReportList() {
      this.loading = true
      const res = await this.$api.commissionDetailsSelectCommissionDetailsPage({
        ...this.params
      })
      this.reportData = res.records
      this.totalCount = res.total
      this.loading = false
    },
    _add() {
      this.$refs.addRef.handleOpen()
    },
    search() {
      this.params.pageNum = 1
      this.getReportList()
    },
    cancer(row) {
      const data = {
        id: row.id,
        status: 4,
      }
      this.$confirm(`确认取消提成吗？`)
          .then((_) => {
            this.$api.commissionDetailsCancelCommission(data).then((res) => {
              if (res) {
                this.$message.success('取消成功！')
                this.getReportList()
              }
            })
          })
          .catch((_) => {
            return
          })
    },
    selectTime(val) {
      if (val) {
        this.params.startTime = dayjs(val[0]).format('YYYY-MM-DD')
        this.params.endTime = dayjs(val[1]).format('YYYY-MM-DD')
      } else {
        this.params.startTime = ''
        this.params.endTime = ''
      }
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getReportList()
    },
    handleCurrentChange(val) {
      this.params.pageNum = val
      this.getReportList()
    },
    receiveData(val) {
      if (val == 1) this.getReportList()
    },
    // handleClick(tab, event) {
    //   console.log(this.activeName)
    //   const data = {
    //     startTime: this.params.startTime || "",
    //     endTime: this.params.endTime || "",
    //     type: this.activeName
    //   }
    //   this.$api.orderGetCommissionListByType(data).then(res => {
    //     const sortedData = res.data.sort((a, b) => a.installers.localeCompare(b.installers));
    //     this.reportData = sortedData
    //   })
    // },
    // async downloadTotal(val) {
    //   if (!(this.params.startTime && this.params.endTime))
    //     return this.$message.error('请选择开始时间和结束时间！')
    //   let params = {
    //     pageSize: 10000,
    //     pageNum: 1,
    //     startTime: this.params.startTime,
    //     endTime: this.params.endTime,
    //     systemType: val,
    //   }
    //   const res = await this.$api.orderGetCommissionSummary(params).then()
    //   //以installers 作为唯一标识  数据汇总为commissionFee   type为1时取commissionFee1    4为commissionFee4
    //   const result = []
    //   const map = new Map()
    //   res.data.forEach((item) => {
    //     const {installers, type, commissionFee} = item
    //
    //     if (!map.has(installers)) {
    //       map.set(installers, {installers})
    //     }
    //     if (type === 1) {
    //       map.get(installers).commissionFee1 = commissionFee
    //     } else if (type === 2) {
    //       map.get(installers).commissionFee2 = commissionFee
    //     } else if (type === 3) {
    //       map.get(installers).commissionFee3 = commissionFee
    //     } else if (type === 4) {
    //       map.get(installers).commissionFee4 = commissionFee
    //     } else if (type === 5) {
    //       map.get(installers).commissionFee5 = commissionFee
    //     }
    //   })
    //   result.push(...map.values())
    //   const wb = XLSX.utils.book_new()
    //   let data = [
    //     [this.params.startTime + '-' + this.params.endTime + '提成汇总'],
    //     [
    //       '姓名',
    //       '安装提成',
    //       '拣货提成',
    //       '装车提成',
    //       '卸货提成',
    //       '售后提成',
    //       '合计',
    //     ],
    //   ]
    //   result.map((el) => {
    //     // el.total = Decimal(el.commissionFee1).plus(Decimal(el.commissionFee4)).toNumber();
    //     el.commissionFee1 ||= 0
    //     el.commissionFee2 ||= 0
    //     el.commissionFee3 ||= 0
    //     el.commissionFee4 ||= 0
    //     el.commissionFee5 ||= 0
    //     el.count1 = Decimal(el.commissionFee1)
    //         .plus(Decimal(el.commissionFee2))
    //         .toNumber()
    //     el.count2 = Decimal(el.commissionFee3)
    //         .plus(Decimal(el.commissionFee4))
    //         .toNumber()
    //     el.count3 = Decimal(el.count1).plus(Decimal(el.count2)).toNumber()
    //     el.total = Decimal(el.count3)
    //         .plus(Decimal(el.commissionFee5))
    //         .toNumber()
    //     data.push([
    //       el.installers,
    //       el.commissionFee1,
    //       el.commissionFee2,
    //       el.commissionFee3,
    //       el.commissionFee4,
    //       el.commissionFee5,
    //       el.total,
    //     ])
    //   })
    //   const ws = XLSX.utils.aoa_to_sheet(data)
    //   ws['!cols'] = [
    //     {wpx: 100}, // 第一列宽度为250单位
    //     {wpx: 100},
    //     {wpx: 100},
    //     {wpx: 100},
    //     {wpx: 100},
    //     {wpx: 100},
    //     {wpx: 100},
    //   ]
    //   ws['A1'].s = {
    //     alignment: {horizontal: 'center'},
    //     font: {bold: true, color: {rgb: '000000'}},
    //     fill: {fgColor: {rgb: 'ff6a00'}},
    //   }
    //   const range = ['A2', 'B2', 'C2', 'D2', 'E2', 'F2'] // 目标单元格范围
    //   const style = {
    //     alignment: {horizontal: 'center'},
    //     font: {bold: true, color: {rgb: '000000'}},
    //     fill: {fgColor: {rgb: '3CB371'}},
    //   }
    //
    //   // 遍历每个单元格并应用样式
    //   range.forEach((cell) => {
    //     ws[cell].s = style
    //   })
    //   ws['A1'].hpt = 240
    //   Object.keys(ws).forEach((cell) => {
    //     if (cell[0] !== '!') {
    //       // 排除特殊属性，如 `!ref`
    //       if (!ws[cell].s) {
    //         ws[cell].s = {} // 确保 `s` 存在
    //       }
    //       if (!ws[cell].s.alignment) {
    //         ws[cell].s.alignment = {}
    //       }
    //       ws[cell].s.alignment.horizontal = 'center'
    //     }
    //   })
    //   XLSX.utils.book_append_sheet(wb, ws, '提成汇总')
    //   ws['!merges'] = [{s: {r: 0, c: 0}, e: {r: 0, c: 5}}]
    //   const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'})
    //   // 创建一个 Blob 对象
    //   const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'})
    //   // 使用 Blob 对象创建一个链接
    //   const link = document.createElement('a')
    //   link.href = URL.createObjectURL(blob)
    //   link.download = `${this.params.startTime}-${this.params.endTime}提成汇总.xlsx`
    //
    //   // 触发下载
    //   link.click()
    //
    //   // 清理
    //   URL.revokeObjectURL(link.href)
    //
    //   function s2ab(s) {
    //     const buf = new ArrayBuffer(s.length)
    //     const view = new Uint8Array(buf)
    //     for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    //     return buf
    //   }
    // },
    // async load_az(val) {
    //   const params = {
    //     startTime: this.params.startTime || '',
    //     endTime: this.params.endTime || '',
    //     type: this.activeName,
    //     pageNum: 1,
    //     areaId: this.areaId,
    //     pageSize: 100000,
    //     installers: this.installers,
    //     storeName: this.storeName,
    //     systemType: this.systemType,
    //     // isCancelCommission:Number(this.isCancelCommission)
    //   }
    //   const resData = await this.$api
    //       .orderGetCommissionListByType(params)
    //       .catch(() => null)
    //   // 1. 获取数据
    //   if (!resData?.data?.length) {
    //     this.$message.warning('暂无数据导出')
    //     return
    //   }
    //   const sortedData = resData.data.sort((a, b) =>
    //       a.storeName.localeCompare(b.storeName)
    //   )
    //   // 遍历数据并计算相同 storeName 的 installers 总和
    //   let totalCommissionMap = {}
    //   sortedData.forEach((item) => {
    //     if (item.isCancelCommission != 0) {
    //       item.commissionFee = 0
    //     }
    //     if (!totalCommissionMap[item.storeName]) {
    //       totalCommissionMap[item.storeName] = 0
    //     }
    //     totalCommissionMap[item.storeName] += item.commissionFee
    //   })
    //   // 将commissionFee添加到每个数据项
    //   const result = sortedData.map((item) => ({
    //     ...item,
    //     totalCommissionFee: totalCommissionMap[item.storeName],
    //     isCancelCommissionStr:
    //         item.isCancelCommission === 0 ? '正常' : '已取消提成',
    //   }))
    //   result.sort((a, b) =>
    //       (a.storeName || '').localeCompare(b.storeName || '')
    //   )
    //   // 3. 组装表格数据
    //   const header = [
    //     '店铺名称',
    //     '所属仓库',
    //     '该店总数',
    //     `${val}姓名`,
    //     `单次${val}费用`,
    //     `${val}日期`,
    //     '状态',
    //   ]
    //   const sheetData = [
    //     [`${val}提成汇总`],
    //     header,
    //     ...result.map((el) => [
    //       el.storeName,
    //       el.areaName,
    //       el.totalCommissionFee,
    //       el.installers,
    //       el.commissionFee,
    //       el.deliveryDate,
    //       el.isCancelCommissionStr,
    //     ]),
    //   ]
    //   // 4. 创建 Sheet
    //   const ws = XLSX.utils.aoa_to_sheet(sheetData)
    //   // 设置第一列和第二列居中
    //   // 样式工具函数
    //   const setStyle = (cell, style) => {
    //     if (!ws[cell]) return
    //     ws[cell].s = {...(ws[cell].s || {}), ...style}
    //   }
    //
    //   // 标题行样式
    //   setStyle('A1', {
    //     alignment: {horizontal: 'center'},
    //     font: {bold: true, color: {rgb: '000000'}},
    //     fill: {fgColor: {rgb: 'FF6A00'}},
    //   })
    //
    //   // 表头样式
    //   header.forEach((_, idx) => {
    //     const cell = String.fromCharCode(65 + idx) + '2' // A2 ~ G2
    //     setStyle(cell, {
    //       alignment: {horizontal: 'center'},
    //       font: {bold: true, color: {rgb: '000000'}},
    //       fill: {fgColor: {rgb: '3CB371'}},
    //     })
    //   })
    //   const range = XLSX.utils.decode_range(ws['!ref']) // 获取工作表范围
    //   for (let R = range.s.r; R <= range.e.r; R++) {
    //     for (let C = range.s.c; C <= range.e.c; C++) {
    //       const cellAddress = {r: R, c: C} // 获取单元格地址
    //       const cell = ws[XLSX.utils.encode_cell(cellAddress)]
    //       if (cell) {
    //         cell.s = cell.s || {} // 初始化样式
    //         cell.s.alignment = {
    //           horizontal: 'center', // 水平居中
    //           vertical: 'center', // 垂直居中
    //         }
    //       }
    //     }
    //   }
    //
    //   // 列宽
    //   ws['!cols'] = Array(header.length).fill({wpx: 150})
    //   // 合并标题行
    //   ws['!merges'] = [{s: {r: 0, c: 0}, e: {r: 0, c: header.length - 1}}]
    //   // 合并相同店铺名称（A列 = colIndex 0）
    //   this.mergeSameCells(ws, sheetData, 0)
    //   // this.mergeSameCells(ws, sheetData, 2);
    //   // 5. 生成工作簿
    //   const wb = XLSX.utils.book_new()
    //   XLSX.utils.book_append_sheet(wb, ws, '提成汇总')
    //   // 6. 导出下载
    //   this.downloadExcel(wb, `${val}提成汇总.xlsx`)
    // },
    // async load_azer(val) {
    //   const params = {
    //     startTime: this.params.startTime || '',
    //     endTime: this.params.endTime || '',
    //     type: this.activeName,
    //     pageNum: 1,
    //     areaId: this.areaId,
    //     pageSize: 100000,
    //     installers: this.installers,
    //     storeName: this.storeName,
    //     systemType: this.systemType,
    //     // isCancelCommission:Number(this.isCancelCommission)
    //   }
    //   const resData = await this.$api
    //       .orderGetCommissionListByType(params)
    //       .catch(() => null)
    //   const data = resData.data
    //   // 获取所有唯一的 installers 和 storeName
    //   const commissions = Array.from(
    //       new Set(data.map((item) => item.installers))
    //   )
    //   const stores = Array.from(new Set(data.map((item) => item.storeName)))
    //   const sheetData = []
    //   // 添加表头
    //   sheetData.push(['店铺名称', ...commissions])
    //   // 为每个 store 添加行
    //   stores.forEach((store) => {
    //     const row = [store]
    //     commissions.forEach((commission) => {
    //       const commissionData = data.find(
    //           (item) => item.storeName === store && item.installers === commission
    //       )
    //       row.push(commissionData ? commissionData.commissionFee : 0) // 如果找不到该项，填充 0
    //     })
    //     sheetData.push(row)
    //   })
    //
    //   // 创建工作表和工作簿
    //   const ws = XLSX.utils.aoa_to_sheet(sheetData)
    //   const wb = XLSX.utils.book_new()
    //   XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
    //   ws['!cols'] = [
    //     {wpx: 200}, // 第一列宽度（Store Name列）
    //     ...commissions.map(() => ({wpx: 80})), // 其余列宽度
    //   ]
    //   // 设置居中对齐
    //   const range = XLSX.utils.decode_range(ws['!ref']) // 获取工作表范围
    //   for (let R = range.s.r; R <= range.e.r; R++) {
    //     for (let C = range.s.c; C <= range.e.c; C++) {
    //       const cellAddress = {r: R, c: C} // 获取单元格地址
    //       const cell = ws[XLSX.utils.encode_cell(cellAddress)]
    //       if (cell) {
    //         cell.s = cell.s || {} // 初始化样式
    //         cell.s.alignment = {
    //           horizontal: 'center', // 水平居中
    //           vertical: 'center', // 垂直居中
    //         }
    //       }
    //     }
    //   }
    //   // 生成并下载 Excel 文件
    //   XLSX.writeFile(wb, `${val}总提成表.xlsx`)
    // },
    // mergeSameCells(ws, data, colIndex, startRow = 2) {
    //   let merges = ws['!merges'] || []
    //   let prevValue = null
    //   for (let row = startRow; row < data.length; row++) {
    //     const value = data[row][colIndex]
    //     if (value === prevValue) {
    //       // 扩展上一段合并范围
    //       merges[merges.length - 1].e.r = row
    //     } else {
    //       prevValue = value
    //       merges.push({
    //         s: {r: row, c: colIndex},
    //         e: {r: row, c: colIndex},
    //       })
    //     }
    //   }
    //   ws['!merges'] = merges
    // },
    // downloadExcel(wb, fileName) {
    //   const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'})
    //   const s2ab = (s) => {
    //     const buf = new ArrayBuffer(s.length)
    //     const view = new Uint8Array(buf)
    //     for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
    //     return buf
    //   }
    //   const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'})
    //   const link = document.createElement('a')
    //   link.href = URL.createObjectURL(blob)
    //   link.download = fileName
    //   document.body.appendChild(link)
    //   link.click()
    //   setTimeout(() => {
    //     URL.revokeObjectURL(link.href)
    //     document.body.removeChild(link)
    //   }, 100)
    // },
  },
}
</script>

<style scoped lang="less">
.box {
  display: flex;
  flex-direction: column;
  align-items: center;

  span {
    display: inline-block;
    text-align: left;
    width: 100px;
  }
}

///* 保证表头和内容都使用自动布局 */
///deep/ .auto-width-table .el-table__header{
//  table-layout: auto !important;
//}
/////deep/ .auto-width-table .el-table__body {
////  table-layout: auto !important;
////}
//
///* 内容不换行，列可被撑宽 */
///deep/ .auto-width-table .cell {
//  white-space: nowrap;
//}

///* 避免滚动条导致表头错位 */
///deep/ .auto-width-table .el-table__header-wrapper,
///deep/ .auto-width-table .el-table__body-wrapper {
//  overflow-x: visible !important;
//}
</style>
